$(function () {
    /**
     * 加载当前历史消息和访客信息
     */
    we_im_load_Visitors(currentvisiid);
    we_im_load_record_Lists(currentvisiid, 'top');

    mInitShortcut();

    const addEditor = new window.wangEditor('#addReply #reply-content');
    const editEditor = new window.wangEditor('#editReply #reply-content');

    /**
     * 加载编辑器
     */
    we_im_load_wangEditor(addEditor);
    we_im_load_wangEditor(editEditor);

    /**
     * 显示当前对话和快捷回复和黑名单
     */
    we_im_ShowChats();
    we_im_ShowBlacklist();
    we_im_getGroupList();

    /**
     * 点击游客
     */
    $('body').on('click', '.tab-content .list-group .list-group-item', function () {
        var obj = $(this);
        var vsid = obj.attr('vsid');
        $('#top_div').attr('page', 1);
        $('.conversation').html("");
        $('#wrap').attr('class', 'current-visi-' + vsid);
        we_im_load_Visitors(vsid);
        we_im_load_record_Lists(vsid, 'top');
        $('.chatbox').removeClass('hide');
        $('.pages-empty-box').addClass('hide');
        obj.find('.notice-icon').addClass('hide').text("");
        Cookies.set('currentvisiid', vsid);
        // Cookies.set('unread_list_number_' + vsid, 0);
        unread('clean','{"uid":"'+vsid+'"}',function (result) {
            console.log('点击游客',result);
        });
        obj.addClass('d4e8ff').siblings().removeClass('d4e8ff');
        if (!IsPC()) {
            $('.left-chat-lists-show').hide();
        }
    });

    /**
     * 获取当前分组快捷回复列表
     */
    $('body').on('click', '.plusgroup .panel h4 a', function () {
        var obj = $(this);
        if (obj.attr('aria-expanded') == 'false') {
            we_im_update_reply_lists(obj.attr('group-id'));
        }
    });

    /**
     * 删除分组
     */
    $('body').on('click', '.plusgroup .panel-heading .icon-shanchu', function () {
        var obj = $(this);
        var confirm = layer.confirm('该分组下的所有记录将被删除！确认要删除？', {
            btn: ['删除', '取消']
        }, function () {
            var group_id = obj.parent().attr('group-id');
            $.post(IM_config.delgroup, {group_id: group_id}, function (res) {
                layer.close(confirm);
                $('.group-' + group_id).remove();
                we_im_msg('删除成功');
            });
        });
    });

    /**
     * 删除快捷回复
     */
    $('body').on('click', '.plusgroup .reply_lists .icon-shanchu', function () {
        var obj = $(this);
        layer.confirm('确认要删除？', {
            btn: ['删除', '取消']
        }, function () {
            var reply_id = obj.parent().attr('reply-id');
            $.post(IM_config.delreply, {reply_id: reply_id}, function (res) {
                $('.reply-' + reply_id).remove();
                we_im_msg('删除成功');
            });
        });
    });

    /**
     * 修改分组
     */
    $('body').on('click', '.plusgroup .panel-heading .icon-xiugai', function () {
        var obj = $(this);
        var group_id = obj.parent().attr('group-id');
        $('#editgroupModal .btn-primary').attr('group-id', group_id);
        $('#editGroup #group-name-edit').val(obj.parent().attr('group-name'));
    });

    /**
     * 修改快捷回复
     */
    $('body').on('click', '.plusgroup .reply_lists .icon-xiugai', function () {
        var obj = $(this);
        var reply_id = obj.parent().attr('reply-id');
        editEditor.txt.html(obj.parent().siblings('textarea').val());
        $('#editreplyModal .btn-primary').attr('reply-id', reply_id);
        $('#editReply #reply-title-edit').val(obj.parent().attr('reply-title'));
    });

    /**
     * 点击脸图片
     */
    $('body').on('click', '.wl_faces_main li', function () {
        var obj = $(this);
        var txt = $('#text_in').html() + obj.find('img').attr('title');
        // insertAtCaret($("#text_textarea"), txt);
        $('#text_in').html(txt);
    });

    $(document).mouseup(function (e) {
        var _con = $('#face_icon');
        if (!_con.is(e.target) && _con.has(e.target).length === 0) {
            $('.tool_box').hide();
        }
    });

    /**
     * 点击聊天内容中的图片
     */
    $('body').on('click', '.chatmsg pre img', function () {
        layer.photos({
            photos: {
                "data": [{
                    src: $(this).attr('src')
                }]
            }
            , anim: 5
        });
    });

    /**
     * 点击快捷回复到输入框
     */
    $('body').on('click', '.reply_lists .reply-span', function () {
        $('#text_in').html($(this).siblings('#reply-cont').val());
        $(".ant-drawer-mask").click();
    });

    /**
     * 鼠标头像悬浮信息
     */
    // $('#wrap').on('mouseenter', '.say-right .cu_pic', function () {
    //     var tips = '<div id="subject-tip" class="screening-tip">
    //         <div class="subject-tip-bd">
    //             <ul>
    //                 <li>
    //                     <span>来源</span>
    //                 </li>
    //                 <li>
    //                     <span>城市</span>
    //                 </li>
    //             </ul>
    //         </div>
    //     </div>';
    //     $('body').append(tips);
    //     chatsTip($(this));
    // });

    /**
     * 鼠标头像悬浮信息
     */
    // $('#wrap').on('mouseout', '.say-right .cu_pic', function () {
    //     $('#subject-tip').remove();
    // });

    /**
     * 点击出现右侧信息
     */
    $(".mdi-comment-processing").click(function () {
        $('.ant-drawer-right').addClass('ant-drawer-open');
        $('.ant-drawer-content-wrapper').css('transform', 'initial');
    });

    $(".ant-drawer-mask").click(function () {
        $('.ant-drawer-right').removeClass('ant-drawer-open');
        $('.ant-drawer-content-wrapper').css('transform', 'translateX(100%)');
    });

    $(".guke-list-info input[type='text']").blur(function () {
        var obj = $(this);
        $.post(IM_config.updateVisitors, {
            key: obj.attr('val'),
            val: obj.val(),
            vinid: $('#basic-id').val()
        }, function (r) {
            if (r.code == 200) {
                return we_im_msg('修改成功');
            }
        });
    });

    /**
     * 加入黑名单
     */
    $('body').on('click', '#blacklist', function () {
        var curvsid = Cookies.get('currentvisiid');
        $.post(IM_config.joinBlacklist, {
            curvsid: curvsid
        }, function (r) {
            if (r.code == 200) {
                $('#logue-item-' + curvsid).remove();
                we_im_ShowBlacklist();
                return we_im_msg(r.data);
            }
        });
    });

    /**
     * 移除黑名单
     */
    $('body').on('click', '#tab-4 .am-btn-danger .icon-shanchu', function () {
        var blid = $(this).attr('data-id');
        $.post(IM_config.delBlacklist, {
            blid: blid,
            vsid: $(this).attr('data-vsid')
        }, function (r) {
            if (r.code == 200) {
                $('#blacklist-' + blid).remove();
                we_im_ShowChats();
                return we_im_msg(r.data);
            }
        });
    });

    /**
     * 客服转接
     */
    $('.transfer_service').click(function () {
        $.post(IM_config.getCustomerLists, function (r) {
            if (r.code == 200) {
                var content = '<ul class="list-group">';
                $.each(r.data, function (index, item) {
                    var jiagray = item.state == 0 ? ' jiagray' : '';
                    var status = item.online_status == 0 ? ' offline-avatar ' : '' ;
                    content += '<li class="list-group-item' + jiagray + ' zj_lists" id="logue-item-' + item.id + '" cuid="' + item.id + '">' +
                        '<div class="visiter">' +
                        '<div class="visit_content">' +
                        '<img class="am-radius '+status+' v-avatar icon_gray" src="' + item.avatar + '" width="50px" height="50px">' +
                        '<span class="c_name">' + item.nick + '</span>' +
                        '<button class="btn btn-round btn-success" status="'+item.online_status+'" cuid="' + item.id + '" avatar="' + item.avatar + '" nick="' + item.nick + '">转接</button>' +
                        '</div>' +
                        '</div>' +
                        '</li>';
                });
                content += '</ul>';
                layer.open({
                    type: 1,
                    title: '客服转接列表',
                    skin: 'layui-layer-rim-top',
                    area: ['420px', '260px'],
                    content: content
                });
            }
        });
    });

    /**
     * 历史记录
     */
    $('.historical_record').click(function () {
        layer.open({
            type: 2,
            title: '历史记录',
            skin: 'layui-layer-rim-record',
            area: ['500px', '550px'],
            content: IM_config.OneHistoryPage
        });
    });

    /**
     * 转接操作
     */
    $('body').on('click', '.zj_lists .btn-success', function () {

        var obj = $(this);

        if( obj.attr('status') == 0 ){
            we_im_msg('转接客服不在线');
            return false ;
        }

        // 删除当前对话
        var yk_id = Cookies.get('currentvisiid');
        var zj_kf_id = obj.attr('cuid');

        $.post(IM_config.transfer, {vsid: yk_id,kfid:zj_kf_id}, function (r) {
           
            if (r.code == 200) {
                obj.attr('disabled', 'disabled').text('转接中...');
                setTimeout(function () {
                    var kf_name = obj.attr('nick');
                    var kf_avatar = obj.attr('avatar');
                    // var zj_kf_id = obj.attr('cuid');
                    var yk_info = '{"type":"transfer","ys_kf_id":"' + IM_user.from_id + '","zj_kf_id":"' + zj_kf_id + '","yk_id":' + yk_id + ',"zj_kf_name":"' + kf_name + '","zj_kf_avatar":"' + kf_avatar + '","group":"' + IM_user.from_group + '"}';
                    $('#logue-item-' + yk_id).remove();
                    Cookies.set('currentvisiid', null);
                    WS.send(yk_info);
                    we_im_msg(r.data);
                    setTimeout(function () {
                        window.location.reload();
                    }, 1000);
                }, 2000);
            }
        });

        return ;
        // 废弃以前的转接操作
        $.post(IM_config.delDialogue, {vsid: yk_id}, function (r) {
            if (r.code == 200) {
                obj.attr('disabled', 'disabled').text('转接中...');
                setTimeout(function () {
                    var kf_name = obj.attr('nick');
                    var kf_avatar = obj.attr('avatar');
                    var zj_kf_id = obj.attr('cuid');
                    var yk_info = '{"type":"transfer","ys_kf_id":"' + IM_user.from_id + '","zj_kf_id":"' + zj_kf_id + '","yk_id":' + yk_id + ',"zj_kf_name":"' + kf_name + '","zj_kf_avatar":"' + kf_avatar + '","group":"' + IM_user.from_group + '"}';
                    $('#logue-item-' + yk_id).remove();
                    Cookies.set('currentvisiid', null);
                    WS.send(yk_info);
                    we_im_msg(r.data);
                    setTimeout(function () {
                        window.location.reload();
                    }, 1000);
                }, 2000);
            }
        });
    });

    /**
     * 聊天记录中的语音播放
     */
    $('body').on('click', '.chatmsg .mess-audio', function () {
        playAudio($(this));
    });

    /**
     * 显示左边
     */
    $('.left-chat-lists-bar').click(function () {
        $('.left-chat-lists-show').toggle();
        if (!$('.right-chat-lists-show').is(':hidden')) {
            $('.right-chat-lists-show').hide();
        }
    });

    /**
     * 显示右边
     */
    $('.right-chat-lists-bar').click(function () {
        $('.right-chat-lists-show').toggle();
        if (!$('.left-chat-lists-show').is(':hidden')) {
            $('.left-chat-lists-show').hide();
        }
    });

    /**
     * 显示发送快捷键
     */
    $('#showinfo').click(function () {
        var shortcuts = Cookies.get('admin-shortcuts');
        if (!shortcuts) {
            Cookies.get('admin-shortcuts', 2);
            shortcuts = 2;
        }
        $('#fuceng').toggle();
        if (shortcuts == 1) {
            $('#type1').addClass('selected-li');
            $('#type2').removeClass('selected-li');
        } else {
            $('#type2').addClass('selected-li');
            $(' #type1').removeClass('selected-li');
        }
    });

    $(document).keypress(function (e) {
        var shortcuts = Cookies.get('admin-shortcuts');
        if ((e.which == 13 && e.ctrlKey) || (e.which == 10 && e.ctrlKey)) {
            var content = $.trim($('#text_in').html());
            $("#text_in").html(content + "<br/>\n");
            if (shortcuts == 2) {
                $('#send').click();
            }
        } else if (e.which == 13) {
            if (shortcuts == 1) {
                $('#send').click();
            }
        }
    });

    /**
     * 点击发送快捷键
     */
    $('#fuceng ul li').click(function () {
        Cookies.set('admin-shortcuts', $(this).attr('type'));
        $(this).addClass('selected-li').siblings().removeClass('selected-li');
    });
});

function keepLastIndex(obj) {
    console.log(obj)
    console.log(window.getSelection)
    console.log(document.selection)
    if (window.getSelection) { //ie11 10 9 ff safari
        obj.focus(); //解决ff不获取焦点无法定位问题
        var range = window.getSelection(); //创建range
        range.selectAllChildren(obj); //range 选择obj下所有子内容
        range.collapseToEnd(); //光标移至最后
    } else if (document.selection) { //ie10 9 8 7 6 5
        var range = document.selection.createRange(); //创建选择对象
        //var range = document.body.createTextRange();
        range.moveToElementText(obj); //range定位到obj
        range.collapse(false); //光标移至最后
        range.select();
    }
}

// 播放暂停切换
function playAudio(mess) {
    var media = mess.find('audio')[0];
    media_play(media);
    mess.find('i').addClass('weight');
    media.onended = function () {
        mess.find('i').removeClass('weight');
    };
    // var media = mess.find('audio')[0];
    // if(media.paused) {
    //     media_play(media);
    //     mess.find('i').addClass('weight');
    // } else {
    //     media_pause(media);
    //     mess.find('i').removeClass('weight');
    // }
    // media.onended = function () {
    //     mess.find('i').removeClass('weight');
    // };
}

// 播放
function media_play(media) {
    media.play();
}

// 暂停
function media_pause(media) {
    media.pause();
}

/**
 * 更新当前游客地址
 */
function we_im_load_ip_info(vsid) {
    $.post(IM_config.getIpinfo, {vsid: vsid}, function (r) {
        if (r.code == 200) {
            $('#basic-city').text(r.data);
        }
    });
}

function chatsTip(e) {
    var eLeft = e.offset().left,
        eTop = e.offset().top,
        eWidth = e.innerWidth(),
        tipw = e[0].offsetWidth,
        top, left;
    left = (eLeft - tipw / 2) + eWidth / 2;
    if (eTop < 60) {
        top = 70;
    } else {
        top = eTop;
    }
    $('#subject-tip').css({
        top: top,
        left: left - 216
    });
}

/**
 * 获取消息列表内容
 * @param vsid 游客id
 */
function we_im_load_record_Lists(vsid, direction) {
    if (!vsid) {
        return false;
    }
    var top = $('#top_div');
    var load_page = parseInt(top.attr('page'));
    $.ajax({
        type: "post",
        url: IM_config.loadRecordLists,
        data: {
            fromid: IM_user.from_id,
            toid: vsid,
            page: load_page
        },
        dataType: "json",
        success: function (r) {
            console.log(r);
            if (r.code == 200) {
                var message = "";
                $.each(r.data, function (index, item) {
                    if (item.utype == 'say_from') {
                        message += '<li class="chatmsg">' +
                            '<div class="showtime">'+timestamp(item.send_time)+'</div>' +
                            '<div class="say-left">' +
                            '<img class="my-circle se_pic" src="' + item.send_avatar + '" width="50px" height="50px">' +
                            '</div><div class="outer-left">' +
                            '<div class="customer">' +
                            '<pre>' + item.content + '</pre>' +
                            '</div>' +
                            '</div>' +
                            '</li>';
                    } else {
                        message += '<li class="chatmsg">' +
                            '<div class="showtime">'+timestamp(item.send_time)+'</div>' +
                            '<div class="say-right">' +
                            '<img class="my-circle cu_pic" src="' + item.send_avatar + '" width="50px" height="50px">' +
                            '</div>' +
                            '<div class="outer-right">' +
                            '<div class="service">' +
                            '<pre>' + item.content + '</pre>' +
                            '</div>' +
                            '</div>' +
                            '</li>';
                    }
                });
                if (direction == 'bottom') {
                    $('#wrap .conversation').append(message);
                } else {
                    $('#wrap .conversation').prepend(message);
                }
                load_page++;
                top.attr('page', load_page);
                if (r.data.length < 10) {
                    top.attr('sw', 'off');
                } else {
                    top.attr('sw', 'on');
                }
                $("#wrap").animate({
                    scrollTop: $("#wrap").prop("scrollHeight")
                }, 50);
            } else {
                top.attr('page', 1);
                top.attr('sw', 'on');
                $('.conversation').html("");
                $('.chatbox').addClass('hide');
                $('.pages-empty-box').removeClass('hide');
                top.attr('sw', 'off');
            }
        }
    });
}

/**
 * 获取游客信息
 * @param vsid 游客id
 */
function we_im_load_Visitors(vsid) {
    if (!vsid) {
        return false;
    }
    $.post(IM_config.getVisitors, {vsid: vsid}, function (r) {
        if (r.code == 200) {
            $.each(r.data, function (key, val) {
                if (in_array(key, ['id', 'name', 'phone', 'note'])) {
                    $('#basic-' + key).val(val);
                } else if (key == 'avatar') {
                    $('.avatar-box .my-circle').attr('src', val);
                } else if (key == 'city') {
                    if (!val) {
                        we_im_load_ip_info(vsid);
                    } else {
                        $('#basic-city').text(val);
                    }
                } else if (key != 'state') {
                    $('#basic-' + key).text(val);
                }
            });
            setTimeout(function () {
                if( $('#logue-item-' + vsid).find('.v-avatar').hasClass('offline-avatar') ||
                    $('.list-group-item.d4e8ff').find('.v-avatar').hasClass('offline-avatar') ){
                    $('#basic-state').text('离线');
                }else{
                    $('#basic-state').text('在线');
                }
                /*if ($('#logue-item-' + vsid).hasClass('jiagray') || $('.list-group-item.d4e8ff').hasClass('jiagray')) {
                    $('#basic-state').text('离线');
                } else {
                    $('#basic-state').text('在线');
                }*/
            }, 100);
        }
    });
}

/**
 * 插入数据
 */
function insertAtCaret(obj, myValue) {
    var $t = obj[0];
    if (document.selection) {
        this.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
    } else if ($t.selectionStart || $t.selectionStart == '0') {
        var startPos = $t.selectionStart;
        var endPos = $t.selectionEnd;
        var scrollTop = $t.scrollTop;
        $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
        this.focus();
        $t.selectionStart = startPos + myValue.length;
        $t.selectionEnd = startPos + myValue.length;
        $t.scrollTop = scrollTop;
    } else {
        this.value += myValue;
        this.focus();
    }
}

/**
 * 配置html编辑器
 */
function we_im_load_wangEditor(editor) {
    editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'emoticon',
        'image',
        'table',
        'splitLine',
        'undo',
        'redo',
    ];
    editor.config.uploadImgServer = IM_config.uploadimg;
    editor.config.uploadImgMaxSize = 2 * 1024 * 1024;
    editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
    editor.config.uploadImgMaxLength = 5;
    editor.create();
}

function we_im_update_reply_lists(group_id) {
    $('#reply-' + group_id + ' .reply_lists').html("");
    $.ajax({
        type: "post",
        url: IM_config.getreplylist,
        data: {
            group_id: group_id
        },
        dataType: "json",
        success: function (r) {
            if (r.code == 200 && r.data) {
                var lists = "";
                $.each(r.data, function (i, v) {
                    lists += '<p class="reply-' + v.id + '"><span class="reply-span">' + v.title + '</span>' +
                        '<textarea id="reply-cont" style="display:none;">' + v.content + '</textarea>' +
                        '<span reply-id="' + v.id + '" reply-title="' + v.title + '" class="fr">' +
                        '<i class="iconfont icon-xiugai" data-toggle="modal" data-target="#editreplyModal"></i>' +
                        '<i class="iconfont icon-shanchu"></i>' +
                        '</span>' +
                        '</p>';
                });
                $('#reply-' + group_id + ' .reply_lists').html(lists);
            }
        }
    });
}

/**
 * 添加回复分组
 */
function we_im_addGroup(obj) {
    var obj = $(obj);
    var group_name = $.trim($('#addGroup #group-name-add').val());
    if (!group_name) {
        return we_im_msg('分组名称不能为空');
    }
    $.ajax({
        type: "post",
        data: {
            group_name: group_name
        },
        url: IM_config.addgroup,
        dataType: "json",
        success: function (r) {
            we_im_msg(r.data);
            if (r.code == 200) {
                var group = '<div class="panel group-' + r.group_id + '">' +
                    '<div class="panel-heading" role="tab" id="heading-' + r.group_id + '">' +
                    '<h4 class="panel-title">' +
                    '<a group-id="' + r.group_id + '" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse-' + r.group_id + '" aria-expanded="false" aria-controls="collapse-0" class="collapsed">' + group_name + '</a>' +
                    '<span group-id="' + r.group_id + '" group-name="' + group_name + '" class="fr">' +
                    '<i class="iconfont icon-xiugai" data-toggle="modal" data-target="#editgroupModal"></i>' +
                    '<i class="iconfont icon-shanchu"></i>' +
                    '</span>' +
                    '</h4>' +
                    '</div>' +
                    '<div id="collapse-' + r.group_id + '" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading-' + r.group_id + '" aria-expanded="false">' +
                    '<div class="panel-body" id="reply-' + r.group_id + '">' +
                    '<div class="reply_lists"></div>' +
                    '<p class="plusreply" group-id="' + r.group_id + '" data-toggle="modal" data-target="#plusreplyModal"><i class="iconfont icon-plus-line"></i> 添加回复</p>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
                setTimeout(function () {
                    $('.plusgroup').prepend(group);
                    $('#addGroup')[0].reset();
                    obj.siblings('.btn-default').click();
                }, 2000);
            }
        }
    });
}

/**
 * 添加快捷回复
 */
function we_im_addReply(obj) {
    var obj = $(obj);
    var group_id = $('.collapse.in .plusreply').attr('group-id');
    var reply_title = $.trim($('#addReply #reply-title-add').val());
    var reply_content = $.trim($('#addReply .w-e-text').html().replace('<p><br></p>', ''));
    if (!reply_title) {
        return we_im_msg('简要名称不能为空');
    }
    if (!reply_content) {
        return we_im_msg('回复内容不能为空');
    }
    $.ajax({
        type: "post",
        data: {
            group_id: group_id,
            reply_title: reply_title,
            reply_content: reply_content,
        },
        url: IM_config.addreply,
        dataType: "json",
        success: function (r) {
            we_im_msg(r.data);
            if (r.code == 200) {
                we_im_update_reply_lists(group_id);
                setTimeout(function () {
                    $('#addReply')[0].reset();
                    obj.siblings('.btn-default').click();
                }, 2000);
            }
        }
    });
}

/**
 * 获取当前分组列表
 */
function we_im_getGroupList() {
    $.ajax({
        type: "get",
        url: IM_config.getgrouplist,
        dataType: "json",
        success: function (r) {
            if (r.code == 200 && r.data) {
                var lists = "";
                $.each(r.data, function (i, v) {
                    lists += '<div class="panel group-' + v.id + '">' +
                        '<div class="panel-heading" role="tab" id="heading-' + v.id + '">' +
                        '<h4 class="panel-title">' +
                        '<a group-id="' + v.id + '" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse-' + v.id + '" aria-expanded="false" aria-controls="collapse-' + v.id + '">' + v.name + '</a>' +
                        '<span group-id="' + v.id + '" group-name="' + v.name + '" class="fr">' +
                        '<i class="iconfont icon-xiugai" data-toggle="modal" data-target="#editgroupModal"></i>' +
                        '<i class="iconfont icon-shanchu"></i>' +
                        '</span>' +
                        '</h4>' +
                        '</div>' +
                        '<div id="collapse-' + v.id + '" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading-' + v.id + '">' +
                        '<div class="panel-body" id="reply-' + v.id + '">' +
                        '<div class="reply_lists"></div>' +
                        '<p class="plusreply" group-id="' + v.id + '" data-toggle="modal" data-target="#plusreplyModal"><i class="iconfont icon-plus-line"></i> 添加回复</p>' +
                        '</div>' +
                        '</div>' +
                        '</div>';
                });
                $('#accordion').html(lists);
            }
        }
    });
}

/**
 * 修改分组
 * @param obj
 */
function we_im_editGroup(obj) {
    var obj = $(obj);
    var group_name = $.trim($('#editGroup #group-name-edit').val());
    var group_id = obj.attr('group-id');
    if (!group_name) {
        return we_im_msg('分组名称不能为空');
    }
    $.ajax({
        type: "post",
        data: {
            group_id: group_id,
            group_name: group_name
        },
        url: IM_config.editgroup,
        dataType: "json",
        success: function (r) {
            we_im_msg(r.data);
            if (r.code == 200) {
                setTimeout(function () {
                    $('#addGroup')[0].reset();
                    $('.group-' + group_id + ' h4 a').text(group_name);
                    obj.siblings('.btn-default').click();
                }, 2000);
            }
        }
    });
}

/**
 * 修改快捷回复
 * @param obj
 */
function we_im_editReply(obj) {
    var obj = $(obj);
    var reply_id = obj.attr('reply-id');
    var group_id = $('.collapse.in .plusreply').attr('group-id');
    var reply_title = $.trim($('#editReply #reply-title-edit').val());
    var reply_content = $.trim($('#editReply .w-e-text').html().replace('<p><br></p>', ''));
    if (!reply_title) {
        return we_im_msg('简要名称不能为空');
    }
    if (!reply_content) {
        return we_im_msg('回复内容不能为空');
    }
    $.ajax({
        type: "post",
        data: {
            reply_id: reply_id,
            group_id: group_id,
            reply_title: reply_title,
            reply_content: reply_content
        },
        url: IM_config.editreply,
        dataType: "json",
        success: function (r) {
            we_im_msg(r.data);
            if (r.code == 200) {
                setTimeout(function () {
                    $('#addReply')[0].reset();
                    $('.reply-' + reply_id + ' .reply-span').text(reply_title);
                    $('.reply-' + reply_id + ' textarea').val(reply_content);
                    obj.siblings('.btn-default').click();
                }, 2000);
            }
        }
    });
}

/**
 * 对话框展示脸图片
 */
function faceon() {
    let face = "";
    let face_main = $('.wl_faces_main ul');
    if (face_main.find('li').length <= 0) {
        $.each(faces_lists, function (title, img) {
            face += '<li><a href="javascript:;"><img title="' + title + '" src="' + img + '"/></a></li>';
        });
        $('.wl_faces_main ul').html(face);
    }
    $('.tool_box').toggle();
}

/**
 * 显示录音
 */
var index = [9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var num = index.length;
var timer = null; //用于清除计时器
var audio = null;
var recorder = null;
var mp3Blob = null;
var audio_layer = null;

function getaudio() {
    audio_layer = layer.open({
        type: 1,
        title: '',
        skin: 'layui-layer-audio',
        closeBtn: 0,
        anim: 2,
        shadeClose: true,
        content: '<button class="btn btn-round btn-default" onclick="funStart(this);" id="btnStart" disabled>录制</button><button class="btn btn-round btn-default" onclick="funStop(this);" id="btnStop" disabled>发送</button>',
        end: function () {
            clearInterval(timer);
        }
    });
    audio = $('.layui-layer-audio');
    setTimer();
    recorder = new MP3Recorder({
        debug: true,
        funOk: function () {
            btnStart.disabled = false;
        },
        funCancel: function (msg) {
            recorder = null;
        }
    });
}

// 录音轮播
function setTimer() {
    timer = setInterval(function () {
        setTimeout(function () {
            num++;
            audio.css("background", "url('/static/common/images/ic_record@2x.png') no-repeat 28px 16px/64px 104px, url('/static/common/images/ic_record_ripple@2x-" + index[num] + ".png') no-repeat 111.2px 32px/28.8px 88px rgba(0, 0, 0, .7)");
        }, 70);
        if (num >= index.length - 1) {
            num = 0;
        }
    }, 70);
}

function funStart(button) {
    btnStart.disabled = true;
    btnStop.disabled = false;
    recorder.start();
}

function funStop(button) {
    recorder.stop();
    btnStart.disabled = false;
    btnStop.disabled = true;
    recorder.getMp3Blob(function (blob) {
        mp3Blob = blob;
        funUpload();
    });
}

/**
 * 上传音频
 */
function funUpload() {
    var formData = new FormData();
    mp3Blob = new File([mp3Blob], encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3'));
    formData.append('file', mp3Blob);
    $.ajax({
        url: IM_config.ajaxupaudio,
        method: 'post',
        data: formData,
        dataType: 'json',
        processData: false,
        contentType: false,
        cache: false,
        async: false,
        success: function (res) {
            if (res.errno == 0) {
                var to_id = currentvisiid;
                var to_nick = $('#logue-item-' + currentvisiid).find('.c_name').text();
                var to_avatar = $('#logue-item-' + currentvisiid).find('.v-avatar').attr('src');
                var text = "<div class='mess-audio'><audio src='" + res.data[0] + "'></audio><i class='iconfont icon-yuyin'></i></div>";
                playPrompt();
                // utype=say_to代表客服给游客聊天
                var message = '{"data":"' + text + '","type":"say-audio","utype":"say_to","from_id":"' + IM_user.from_id + '","from_nick":"' + IM_user.from_nick + '","from_avatar":"' + IM_user.from_avatar + '","to_id":"' + to_id + '","to_nick":"' + to_nick + '","to_avatar":"' + to_avatar + '"}';
                var pavatar = $('#pavatar-src').val();
                var from_tpl = '<li class="chatmsg">' +
                    '<div class="showtime">'+timestamp()+'</div>' +
                    '<div style="position: absolute;top: 26px;right: 2px;">' +
                    '<img class="my-circle cu_pic" src="' + pavatar + '" width="50px" height="50px">' +
                    '</div>' +
                    '<div class="outer-right">' +
                    '<div class="service">' +
                    '<pre>' + text + '</pre>' +
                    '</div>' +
                    '</div>' +
                    '</li>';
                $('.conversation').append(from_tpl);
                setTimeout(function () {
                    $('#wrap').scrollTop($("#wrap")[0].scrollHeight);
                }, 10);
                WS.send(message);
                layer.close(audio_layer);
            }
        }
    });
}

/**
 * 暂时离开
 */
function loginOut() {
    $(".list-group li").each(function () {
        WS.send(JSON.stringify({
            type: 'close_user',
            toid: $(this).attr('vsid')
        }));
    });
    $.post(IM_config.updateCustomerState, {
        state: 0
    }, function (r) {
        if (r.code == 200) {
            we_im_msg('暂时离开');
            $('.user-state i').attr('class', 'notice user-state-0');
        }
    });
}

/**
 * 我再线上
 */
function myOnline() {
    $.post(IM_config.updateCustomerState, {
        state: 1
    }, function (r) {
        if (r.code == 200) {
            we_im_msg('我线上了');
            $('.user-state i').attr('class', 'notice user-state-1');
        }
    });
}

/**
 * 客服收款
 */
$(".alipay").on('click', function () {

    var openIndex = layer.open({
        type: 2,
        title: '客服收款',
        skin: 'layui-layer-rim-record',
        area: ['300px', 'auto'],
        content: IM_config.customerpay,
        btn: ['确认', '取消',],
        yes: function (index, layero) {

            var to_id = Cookies.get('currentvisiid');
            var to_nick = $('#logue-item-' + to_id).find('.c_name').text();
            var to_avatar = $('#logue-item-' + to_id).find('.v-avatar').attr('src');
            var from_id = IM_user.from_id;
            var from_nick = IM_user.from_nick;
            var from_avatar = IM_user.from_avatar;

            var childframe = layer.getChildFrame('body',openIndex);
            var amount = $(childframe).find('#amount').val();
            var note = $(childframe).find('#beizhu').val();
            var pay_type = $(childframe).find('input[name="pay_type"]:checked').val();
            if (!to_id) {
                layer.msg('请刷新重试')
                return false;
            }
            if (!amount) {
                layer.msg('请输入正确的金额')
                return false;
            }

            var index = layer.load();
            var params = {
                amount: amount,
                note: note,
                to_id: to_id,
                to_nick: to_nick,
                to_avatar: to_avatar,
                from_id: from_id,
                from_nick: from_nick,
                from_avatar: from_avatar,
                pay_type: pay_type,
            };

            hook('customerpay', JSON.stringify(params), 1,function (result) {
                layer.close(index);
                if (result == false || result.status != 'success') {
                    layer.msg(result.message);
                    return false;
                }

                layer.close(openIndex);
            });
        },
    });
});
